/* eslint react/prefer-stateless-function:0, react/prop-types:0 */

import React, { Component } from 'react';
import qs from 'querystring';
import { connect } from 'react-redux';
import Wrapper from './wrapper';
import { Button, Checkbox, Input, Select } from 'antd';
// import ErrorBoundary from '../../components/ErrorBoundary';
import BraftEditor from 'braft-editor/dist/braft';
import 'braft-editor/dist/braft.css';
import style from './style.css';
import * as actions from '../../actions/articleAction';

const Option = Select.Option;

@connect((state) => ({
  article: state.admin.article,
}), actions)
export default class extends Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { updateId, getArticleById, getCategory } = this.props;
    const seprator = location.hash.indexOf('?');
    const querystring = location.hash.slice(seprator + 1);
    const { id } = qs.parse(querystring);
    if (id) {
      updateId(id);
      getArticleById(id);
    }
    getCategory();
  }

  render() {
    const { article, updateCategory, updateContent, updateTitle, updateTop, submit, uploadImg } = this.props;
    const { category = [], id, cid, title, top, content } = article;

    console.log(top);
    console.log(Boolean(top));
    const editorProps = {
      height: 400,
      initialContent: content,
      contentFormat: 'html',
      placeholder: '请填写内容',
      onHTMLChange: updateContent,
      controls: [
        'undo', 'redo', 'split', 'font-size', 'font-family', 'text-color',
        'bold', 'italic', 'underline', 'strike-through', 'text-align', 'split', 'headings', 'list_ul', 'list_ol',
        'split', 'link', 'split', 'media'
      ],
      media: {
        image: true, // 开启图片插入功能
        validateFn: null, // 指定本地校验函数，说明见下文
        uploadFn: uploadImg, // 指定上传函数，说明见下文
        externalMedias: {
          image: false,
          audio: false,
          video: false,
        },
      },
    };
    return (
      <Wrapper openKeys="article" selectedKeys="edit">
        <div className={style.pageTitle}>{id ? '修改文章' : '新增文章'}</div>
        <div style={{ margin: '0 0 15px' }}>
          <Select
            showSearch
            style={{ width: 200 }}
            placeholder="选择栏目"
            optionFilterProp="children"
            onChange={(id) => updateCategory(id)}
            value={cid}
            onFocus={f => f}
            onBlur={f => f}
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
            {
              category.map(item => {
                if (!item.parent_id) {
                  return (
                    <Option value={item.id} key={`category-${item.id}`}>
                      <p style={{ fontWeight: 800 }}>{item.name}</p>
                    </Option>
                  );
                } else {
                  return (
                    <Option value={item.id} key={`category-${item.id}`}>
                      <p style={{ marginLeft: '15px' }}>{item.name}</p>
                    </Option>
                  );
                }
              })
            }

          </Select>
          <span style={{ margin: '0 0 0 15px', color: '#999', fontSize: '12px' }}>（添加文章到此栏目下）</span>
        </div>
        <div style={{ margin: '0 0 15px', width: '500px' }}>
          <Input size="large" value={title} onChange={e => updateTitle(e.target.value)} placeholder="请填写标题" />
        </div>
        <div style={{ margin: '0 0 20px', width: '500px' }}>
          <Checkbox checked={Boolean(top)} onChange={e => updateTop(+e.target.checked)}>
            置顶<span style={{ color: '#999', fontSize: '12px' }}>（勾选后会显示到本栏目第一条，无需置顶则忽略此项）</span>
          </Checkbox>
        </div>
        <div className={style.editor}>
          <BraftEditor {...editorProps} />
        </div>
        {id &&
        <Button type="default" size="small" style={{ marginRight: '20px' }} onClick={() => history.back()}>返回</Button>
        }
        <Button type="primary" size="large" style={{ marginTop: '20px' }} onClick={submit}>提交</Button>
      </Wrapper>
    );
  }
}
